/* mixin */
import tourGuide from '@src/mixins/tourGuide'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'

import { getColumnFields } from '@src/modules/task/taskTypes/planTask/view/fields'

import * as TaskApi from '@src/api/TaskApi.ts';

/* component */
import TaskPlanView from './components/TaskPlanView.vue'
import TaskPlanInfoRecord from './components/TaskPlanInfoRecord.vue'
import TaskListView from './components/TaskPlanTaskList/TaskListView.vue'
import BaseBarV3 from '@src/component/common/BaseTabBar/BaseTabBarV3.vue'


import { computedTabList } from '@src/util/tabBarUtils'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import { BaseTabBarUsualEnum, StorageHttpParamsForTerminalType, StorageHttpParamsForModuleType } from '@src/component/common/BaseTabBar/enum'
import { getStorageForDetailTabbar, setStorageForDetailTabbar, getRichTextContent } from '@src/api/SystemApi'

import { isOpenData, openAccurateTab } from '@src/util/platform'


import i18n from '@src/locales'
import { getOssUrl } from '@src/util/assets'
const noAuthImage = getOssUrl('/no_auth.png')

export default {
  name: 'task-plan-task-detail-view',
  inject: ['initData'],
  mixins: [tourGuide, ThemeMixin],
  data() {
    return {
      noAuthImage,
      loading: false,
      pending: false,
      collapse: true,
      collapsing: false,
      task: {...this.initData},
      fields: getColumnFields(this),

      canViewTask: this.initData?.canViewPlanTask || false,
      leftActiveTab: 'task-plan-view',
      collapseDirection: '',
      rightTabBarLoading:false,
      tabBarList:[],
      rightActiveTab: '',
      rightActiveTabItem:{},

    }
  },
  computed: {
    // 子组件所需的数据
    propsForSubComponents() {
      return {
        task: this.task
      }
    },
    planId() {
      return this.task.id
    },
    // 0 进行中 1 已完成 2 已取消 3 已删除
    notCreated() {
      return this.task.state === 0
    },
    // 允许取消（状态为进行中允许取消）
    canCancel() {
      return this.task.canCancel
    },
    // 允许编辑
    canEdit() {
      return this.task.canEdit
    },
    // 允许复制
    canCopy() {
      return this.task.canCopy
    },
    // 动态信息 添加备注权限
    messageConfig() {
      return this.initData?.messageConfig || {};
    },
    showTaskRecordTemplate() {
      return this.messageConfig.taskRemark === true
    },
  },
  methods: {
    // 折叠
    collapseBtn() {
      this.collapse = !this.collapse;
      // 解决展开时有时会触发内容区域滚动
      if (this.collapse) {
        this.collapsing = true;
        setTimeout(() => {
          this.collapsing = false;
        }, 0)
      }
    },
    refreshFromTab() {
      let fromId = window.frameElement.getAttribute('fromid')
      this.$platform.refreshTab(fromId)
    },
    // 取消
    async cancelTask() {
      this.pending = true;
      let warningMsg = i18n.t('task.tip.planTaskCancelTip')
      const result = await this.$platform.confirm(warningMsg);
      if (!result) return this.pending = false;
      TaskApi.cancelPlanTask({planId: this.planId}).then(res => {
        if (res.success) {
          // this.refreshFromTab()
          window.location.reload();
        } else {
          this.$platform.alert(res.message);
          this.pending = false;
        }
      }).catch(err => {
        console.log(err);
        this.pending = false;
      })
    },
    // 打开编辑工单
    editTask() {
      if(!this.planId) return
      let fromId = window.frameElement.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePlanTaskEdit,
        key: this.planId,
        params:`id=${this.planId}`,
        fromId
      })
    },
    // 复制
    copyTask() {
      if(!this.planId) return
      // let fromId = window.frameElement.getAttribute('id')
      // openAccurateTab({
      //   type: PageRoutesTypeEnum.PagePlanTaskCopy,
      //   key: this.planId,
      //   params:`id=${this.planId}`,
      //   fromId
      // })

      window.location.href = `${this.$resourcePrefix}/task/planTask/copy?id=${this.planId}`;
    },
    // 滚动的距离
    getScroll() {
      this.collapse = false
    },
    async initRightTabBar() {
      let { TabBarListItemKey:tabName, TabBarListItemLabel:tabLabel, TabBarListItemShow:tabShow, TabBarCardInfoType:tabIsCardType, TabCardInfoSingle:tabIsCardSingle, TabBarListItemType:tabType } = BaseTabBarUsualEnum;

      let barArr = [
        {[tabName]: "record", disabled: true, [tabLabel]: i18n.t('task.detail.dynamicInfo'), [tabShow]: true},
        {[tabName]: "planTaskTaskList", disabled: false, [tabLabel]: i18n.t('task.taskTypes.planTask.planTaskWorkOrder'), [tabShow]: true},
      ]
      barArr.forEach(tab => {
        tab.needTrack = true
      })
      let parasm_ = {
        equipment: StorageHttpParamsForTerminalType.PC,
        bizType: StorageHttpParamsForModuleType.TaskPlan,
        bizTypeId: this.task.templateId
      }
      try {
        // 获取tabbar用户行为缓存/*  */
        let storageList = await getStorageForDetailTabbar(parasm_);
        if(storageList.status !== 0) {
          throw storageList.message
        }
        let storageList_ = storageList.data.map(item=>{
          const { cardId, checked} = item;
          return {
            [tabName]:cardId,
            [tabShow]:checked
          }
        })
        barArr = computedTabList(barArr, storageList_)
      } catch (error) {
        console.warn(error, 'error try catch getStorageForDetailTabbar');
      }
      this.$nextTick(()=>{
        let firstItem = barArr && barArr.find(item=>item[tabShow])
        this.rightActiveTab = firstItem?.[tabName];
        this.rightActiveTabItem = firstItem;
        this.rightTabBarLoading = false;
      })
      this.tabBarList = barArr;
    },
    tabBarChangeItem(item){
      let { TabBarListItemKey:tabName,  TabBarListItemType:tabType, TabBarCardInfoType } = BaseTabBarUsualEnum;
      this.$refs.rightContent?.scrollTo(0, 0)
      this.rightActiveTab = item[tabName];
      this.rightActiveTabItem = item;
      
      this.$nextTick(() => {
        this.$refs.TaskPlanDetailMainElement.scrollTop = 0;
      })
      
    },
    // tabbar数据发生变更钩子函数
    tabBarUpdateList(list){
      const { TabBarCardInfoType, TabBarListItemKey:tabName, TabBarListItemShow:tabShow } = BaseTabBarUsualEnum;
      let list_ = list.map(item=>{
        return {
          cardId: item.type == TabBarCardInfoType ? item.id : item[tabName],
          checked: item[tabShow]
        }
      })
      let parasm_ = {
        equipment: StorageHttpParamsForTerminalType.PC,
        bizType: StorageHttpParamsForModuleType.TaskPlan,
        bizTypeId: this.task.templateId,
        cardList :list_
      }
      setStorageForDetailTabbar(parasm_)
    },
  },
  async mounted() {
    this.initRightTabBar()

  },
  components: {
    [TaskPlanView.name]: TaskPlanView,
    TaskPlanInfoRecord,
    [TaskListView.name]: TaskListView,
    BaseBarV3
  }
}